<template>
  <div :class="{'custom-upload-disabled': disabled, 'custom-upload': true}">
    <customEmpty :show="hide" :title="hideMsg"  v-if="!onlyButton"/>

    <t-upload
      ref="uploadRef1"
      :action="cpAction"
      v-model="fileThis"
      :disabled="disabled"
      :autoUpload="autoUpload"
      @remove="remove"
      @success="success"
      :data="data"
      :headers="cpHeaders"
      :theme="theme"
      name="file"
      :formatResponse="formatImgResponse"
      :beforeUpload="beforeUpload"
      :max="max"
      :multiple="multiple"
      :class="{'custom-form-upload-file': theme == 'file', 'custom-form-upload-image': theme == 'image'}"
      v-show="!hide"
    >
    </t-upload>

    <div>
      <customCard :shadow="true" :hide-title="true"
                  v-for="(item, index) in fileList" :key="index"
                  v-if="!onlyButton"
      >
        <template #content>
          <customSpace full-width style="margin-bottom: 5px">
            <template #content style="margin-bottom: 5px">
              <customButton  title="删除" theme="success" size="small" help="删除" @click="remove(item)" v-if="!disabled"/>
              <customButton  title="预览" theme="primary" size="small" help="预览图片"  @click="viewImg(item)"  v-if="isImage(item)"/>
              <customButton  title="预览" theme="primary" size="small" help="预览PDF"  @click="viewPdf(item)"  v-if="isPdf(item)"/>
              <customButton   title="下载" theme="primary" size="small" help="下载"   @click="download(item)"/>
            </template>
          </customSpace>
          <customImage :src="item.url"  :height="60" :width="-1" style="display: inline-block" shape="" v-if="isImage(item)"/>
          <div  v-if="isPdf(item)" style="height: 60px">
            PDF
          </div>
          <div class="div-NoWrap" style="font-size: 11px;line-height: 11px;padding: 5px 0px;">{{item.fileName}}</div>
          <div class="div-NoWrap" style="font-size: 11px;line-height: 11px;zoom: 80%"><strong style="margin-right: 3px">上传时间</strong>{{item.gmtCreate}}</div>
        </template>
      </customCard>
    </div>
    <customEmpty :show="fileList.length == 0 && !hide" title="无附件" v-if="!onlyButton"/>



    <!--    图片预览-->
    <t-image-viewer v-model="imageViewShow" :images="imageViewShowList" :closeOnEscKeydown="false" :closeOnOverlay="false"  v-if="!onlyButton">
    </t-image-viewer>
  </div>
</template>

<script>
import customImage from "@/components/custom/form/customImage.vue"
import customCard from '@/components/custom/layout/customCard'


export default {
  desc: '自定义上传组件',
  name: 'customUpload',
  components: {
    customImage,customCard
  },
  props: {
    /**
     * @Description：是否禁用
     * @Date 2023-10-10
     */
    disabled: {
      type: Boolean,
      default: () => false
    },
    /**
     * @Description：是否自动上传
     * @Date 2023-10-10
     */
    autoUpload: {
      type: Boolean,
      default: () => true
    },
    /**
     * @Description：上传路径
     * @Date 2023-10-10
     */
    action: {
      type: String,
      default: () => ''
    },
    /**
     * @Description：上传请求所需的额外字段
     * @Date 2023-10-10
     */
    data: {
      type: Object,
      default: () => {}
    },
    /**
     * @Description：上传请求所需的额外字段
     * @Date 2023-10-10
     */
    file: {
      type: String,
      default: () => ''
    },
    /**
     * @Description：true 隐藏上传区域
     * @Date 2023-10-10
     */
    hide: {
      type: Boolean,
      default: () => false
    },
    /**
     * @Description：隐藏上传区域后，需要显示的信息
     * @Date 2023-10-10
     */
    hideMsg: {
      type: String,
      default: () => '上传区域已隐藏'
    },
    /**
     * @Description：是否允许上传多个
     * @Date 2023-10-15
     */
    multiple: {
      type: Boolean,
      default: () => false
    },
    /**
     * @Description：最多上传多少个文件
     * @Date 2023-10-15
     */
    max: {
      type: Number,
      default: () => 99
    },
    /**
     * @Description：最多上传多少个文件
     * @Date 2023-10-15
     */
    theme: {
      type: String,
      default: () => 'custom'
    },
    /**
     * @Description：true 仅显示上传按钮
     * @Date 2023-10-15
     */
    onlyButton: {
      type: Boolean,
      default: () => false
    },
  },
  created() {
    let proxyApi = process.env.VUE_APP_BASE_API
    if (proxyApi .indexOf('http') != -1) {
      this.baseApi = location.origin +   '/api'
    } else{
      this.baseApi = location.origin + this.resources.pathRoot +  '/api'
    }

  },
  data() {
    return {
      // 当前文件
      fileThis: [],
      // 当前文件
      fileList: [],
      baseApi: '',

      //图片类型列表
      fileTypeImg: 'JPEG,JPG,PNG,ICON',

      imageViewShow: false,

      imageViewShowList: [],
      // eslint-disable-next-line global-require
      resources: require('@/settings.js')
    }
  },
  methods: {
    // 双穿前
    beforeUpload(param) {
      if (param.size > 1024*1024 * 500 ) {
        this.utilMessage.error('文件大小超过500兆，不支持上传')
        return false
      }
      if (this.autoUpload) {
        this.utilVue.loadShow(true)
      }
    },
    // 上传失败
    success(context) {
      context.file.name = context.file.response.name
    },
    // 图片预览
    viewImg(file) {
      this.imageViewShow = true
      this.imageViewShowList = this.fileList.filter(item => this.isImage(item)).map(item => {
        return item.url.replace(this.baseApi, this.utils.getBaseUrlFull())
      })
    },
    // pdf预览
    viewPdf(file) {
      let home = global.vue.$children[0].$children[0]
      home.pdfUrl = file.url
      home.$refs.customDrawerPdf.show()
    },
    // 下载
    download(file) {
      this.utils.downloadByFile(file)
    },

    // 格式化响应
    formatImgResponse(resp) {
      this.utilVue.loadHide()
      if (resp.code == 0) {
        this.$emit('success', resp.data)
        this.utilMessage.success(resp.msg ? resp.msg: '文件上传成功')
        if (!this.onlyButton) {
          resp.data.url = this.baseApi + resp.data.filePath + '?temp=' + Math.random()
          this.fileList.unshift(resp.data)
        }

        return {}
      }
      this.$emit('error', resp)
      this.utilMessage.error(resp.msg ? resp.msg: '文件上传失败')
      return { }
    },

    // 移除
    remove(item) {
      this.utilMessage.confirm('是否删除该文件?', () => {
        let id = item.id
        this.utilVue.loadShow(true)
        this.$ajax.get(`${this.baseApi}/sys/file/delFilesByRef?fileId=${id}`, {}).then((response) => {
          if (response.code == 0) {
            this.fileList.splice(this.fileList.findIndex(itemFind => itemFind.id == id), 1)
            this.utilMessage.success(response.msg)
            this.$emit('remove')
          }
          this.utilVue.loadHide()
        })
      })
    },
    //加载文件
    loadFiles() {
      this.fileList = []
      let getParam = {}
      getParam.fileRefTable = this.data.fileRefTable
      getParam.fileRefId = this.data.fileRefId
      if (this.strings.isNotBlank(this.data.fileInfoField)) {
        getParam.fileInfoField = this.data.fileInfoField

      }
      if (this.data.fileInfoIdArr && this.data.fileInfoIdArr.length > 0) {
        getParam.fileInfoIdArr = this.data.fileInfoIdArr.join(',')
      }
      this.$ajax.post(`${this.baseApi}/sys/file/getFilesByRef`, getParam).then((response) => {
        if (response.code == 0) {
          let data = response.data
          if (data && data.length > 0) {
            data.forEach(ob => {
              ob.url = this.baseApi + ob.filePath + '?temp=' + Math.random()
            })
            this.fileList = data
          }
        }
      })
    },
    // 文件扩展名
    getExt(file) {
      let name = file.fileName ? file.fileName : ''
      return name.substring(name.lastIndexOf('.')+1).toUpperCase()
    },
    //是否是图片
    isImage(file) {
      return this.fileTypeImg.indexOf(this.getExt(file)) != -1
    },
    //是否是图片
    isPdf(file) {
      let name = file.name ? file.name : ''
      let typeName=name.substring(name.lastIndexOf('.')+1)
      return this.getExt(file) == 'PDF'
    },
    //组件实例
    inst() {
      return this.$refs.uploadRef1
    }
  },
  watch: {
    // 监听表单设置本组件的值
    file: {
      immediate: true, // 初始创建 watch 时立即执行回调函数
      deep: true, // 监听到对象里面的值的变化
      handler() {
        // if (this.strings.isNotBlank(this.file)) {
        //   this.fileThis = [{url: this.file + '?temp=' + Math.random() }]
        // } else {
        //   this.fileThis = []
        // }
      },
    },

    //data 变化后执行
    data: {
      handler(newValue, oldValue) {
        if (this.data && this.data.fileRefId &&  this.cpIsUploadMore && !this.utils.isObjEq(newValue,oldValue)) {
          this.loadFiles()
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    cpIsUploadMore() {
      return this.cpAction.indexOf('/sys/file/uploadMore') != -1
    },
    cpAction() {
      return this.baseApi + this.strings.defaultIfBlank(this.action, '/sys/file/uploadMore')
    },
    cpHeaders() {
      return {
        Authorization: this.utils.getCurrentUser().token
      }
    },
    cpAccept() {
      if (this.theme == 'file') {
        return '*'
      }
      return 'image/*'
    }
  }
}
</script>

<style lang="scss">
.custom-upload-disabled {
  .t-upload__image-add,.t-upload__trigger{
    display:  none !important;
  }
}

.custom-upload{
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  padding: 0px 5px;
  .t-card{
    display: inline-block;
    margin-left: 10px;
    text-align: center;
    width: 150px;
    height: 150px;
  }
  .t-card__body{
    padding:  10px;
  }
}

.custom-form-upload-image{
  .t-icon-add{
    margin-bottom: 0px !important;
  }
  .t-upload__card-container,.t-upload__card-content{
    width: 80px !important;
    height: 50px !important;
  }
  .t-upload__card-name{
    display: none !important;
  }
}

.custom-form-upload-file{
  .t-upload__trigger{
    display: block;
    margin-bottom: 10px;
  }
  .t-upload__single-display-text{
    display: inline-block;
  }
  display: inline-block;
}

</style>
